var util = require('../../utils/util.js')
var app = getApp();
var BaseUrl = util.baseUrl;
var token = util.token;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //红包列表数据
    list: [],
    //从确认订单传过来的数据
    price: "",
    categoryId: "",
    imageWidth: "",
    canuselist: null,
    cannotuselist: null,
    isusedlist: null,
    filterlist:null
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;
    let mohuanUser = getApp().globalData.mohuanUser
    let memberId = mohuanUser.memberId
    console.log("************memberId" + memberId);
    token = mohuanUser["X-AUTH-TOKEN"]
    //接收来自订单确认页面的参数
    that.setData({
      imageWidth: wx.getSystemInfoSync().windowWidth,
      price: options.price,
      categoryId: options.categoryId

    })


    //联网加载数据
    // var that = this;
    // // let mohuanUser = app.globalData.mohuanUser
    // let memberId = mohuanUser.memberId
    // 测试接口  url: `https://testserver1.magicmanufactory.com/c2mwebservice/api/v2/orders/${memberId}/availableRedpackets`
    wx.request({
      url: `https://www.magicmanufactory.com/c2mwebservice/api/v2/orders/${memberId}/availableRedpackets`,
      // url: `https://testserver1.magicmanufactory.com/c2mwebservice/api/v2/orders/${memberId}/availableRedpackets`,
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'C2M-Identify': 'Platform:iOS,APP Version:6.300,OS Version:10.2,Device Type:xiaochengxu',
        'Content-Encoding': 'gzip',
        'X-AUTH-TOKEN': token,
        // 'Cookie': imageid
      },
      data: { "brandGoods": [] },
      success: function (res) {
        console.log(res);
        console.log("*请求成功*****" + JSON.stringify(res))
        //整个红包list
        var list = res.data.returnData["0"].redpacketList
        //可用红包
        var canuselist = new Array();
        var count = 0;
        //不可用list
        var cannotuselist = new Array();
        var cannot = 0;
        //已使用list
        var isusedlist = new Array();
        var isused = 0;
        //红包状态,10未使用，20已使用，30快过期，40已过期，50已占用
        //先修改状态，改变了list中couponState的值
        for (var i = 0; i < list.length; i++) {
          if (list[i].couponState == 50) {
            list[i].couponState = "已占用";
            canuselist[count] = list[i];
            count++;
          } else if (list[i].couponState == 10) {
            list[i].couponState = "可用";
            canuselist[count] = list[i];
            count++;
          } else if (list[i].couponState == 30) {
            list[i].couponState = "快过期";
            canuselist[count] = list[i];
            count++;
          } else if (list[i].couponState == 40) {
            list[i].couponState = "不可用";
            cannotuselist[cannot] = list[i];
            cannot++;
          } else if (list[i].couponState == 20) {
            list[i].couponState = "已使用";
            isusedlist[isused] = list[i];
            isused++;
          }

        }

        console.log("cannotuselist" + JSON.stringify(cannotuselist));
        console.log("isusedlist" + JSON.stringify(isusedlist));
        console.log("canuselist" + JSON.stringify(canuselist));
        //保存数据
        // that.setData({
        //   canuselist: canuselist,
        //   cannotuselist: cannotuselist,
        //   isusedlist: isusedlist
        // })
        for (var i = 0; i < canuselist.length; i++) {
          let shijianchuo = canuselist[i].validTo;
          //  _this._loadFreight(function (res) {
          canuselist[i].showtime = that.timeFormat(shijianchuo);
        }
        for (var i = 0; i < cannotuselist.length; i++) {
          let shijianchuo = cannotuselist[i].validTo;
          //  _this._loadFreight(function (res) {
          cannotuselist[i].showtime = that.timeFormat(shijianchuo);
        }
        for (var i = 0; i < isusedlist.length; i++) {
          let shijianchuo = isusedlist[i].validTo;
          //  _this._loadFreight(function (res) {
          isusedlist[i].showtime = that.timeFormat(shijianchuo);
        }
        that.setData({
          canuselist: canuselist,
          cannotuselist: cannotuselist.slice(0, 4),
          isusedlist:isusedlist
        })



      },
      fail: function (res) {
        console.log("*请求失败*****" + res)

      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },



  //点击单个红包的点击事件,先判断是否可用，不可用弹弹窗 可用传数据，关闭页面
  clickItem: function (e) {
    var that = this;
    //先判断是否可用
    //从确认订单传过来的数据
    //price: "",
    //categoryId:""
    var myDate = new Date();
    let todaytime = myDate.getTime();
    //点击item红包传的值
    let itemprice = e.currentTarget.dataset.price
    let p = e.currentTarget.dataset.pinlei;
    let availabletime = e.currentTarget.dataset.riqi;
    let hongbaoid = e.currentTarget.dataset.hongbaoid;
    let discount = e.currentTarget.dataset.discount;
    //订单确认页面传入的值
    let pr = that.data.price;
    let c = that.data.categoryId;





    console.log("点击单个红包传入的值为" + "品类为" + p + "红包ID为" + hongbaoid + "优惠值为" + discount + "满多少钱使用" + itemprice)
    console.log("P的判断" + p.search(c) != -1)
    console.log("pr此时的值为" + pr)
    console.log("点击item的价格为" + itemprice)


    //1品类判断 2总价格判断 3可用时间判断  4红包状态判断
    //



    let a = parseInt(pr) > parseInt(itemprice)
    console.log(a)
    console.log("时间的判断" + (availabletime > todaytime))
    console.log("红包状态的判断" + ((e.currentTarget.dataset.state == "可用" || e.currentTarget.dataset.state == "快过期")))
    /**
     * 点击单个红包item时判断红包是否可用
     */
    if (p.search(c) != -1 && a && availabletime > todaytime &&
      (e.currentTarget.dataset.state == "可用" || e.currentTarget.dataset.state == "快过期")) {
      console.log("红包可用")
      //红包可用，back到订单页面，传递优惠值，红包ID，红包类型三个值，用缓存传值
      wx.setStorage({
        key: "mydata",
        data: {
          discount: discount,
          hongbaotype: p,
          id: hongbaoid,
        },
        success: function () {
          wx.navigateBack();   //返回上一个页面
        }
      })

    } else {
      console.log("红包不可用");
      wx.showToast({
        title: '红包不可用',
        icon: 'succes',
        duration: 1000
      })
    }
    console.log("点击的品类为" + e.currentTarget.dataset.pinlei);



    console.log("点击事件传入的数据" + JSON.stringify(e.currentTarget));
    console.log(e.currentTarget.dataset.price);

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  timeFormat: function (nS) {
    return new Date(parseInt(("/Date(" + nS + ")/").substr(6, 13))).toLocaleDateString();
  },
})